package com.xpq.petserver.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xpq.petserver.entity.response.GeneralResponse;
import com.xpq.petserver.util.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT处理拦截器
 * @author XPQ
 * @date 2022-03-04
 * */
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        Map<String, Object> map = new HashMap<>();
        GeneralResponse generalResponse1 = new GeneralResponse();
        generalResponse1.setCode(401);
        //获取请求头中的令牌
        String token = request.getHeader("token");

        try {
            if(token != null) {
                JWTUtils.verify(token);//验证令牌
                return true;//放行请求
            }else {
                generalResponse1.setMsg("您尚未登录，请登录！");
            }
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
//            map.put("msg", "无效签名！");
            generalResponse1.setMsg("您尚未登录，请登录！");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
//            map.put("msg", "token过期！");
            generalResponse1.setMsg("登录过期，请重新登录！");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
//            map.put("msg", "token算法不一致！");
            generalResponse1.setMsg("身份验证失败，请重新登录！");
        } catch (Exception e) {
            e.printStackTrace();
//            map.put("msg", "token无效！");
            generalResponse1.setMsg("身份验证失败，请重新登录！");
        }
//        map.put("state", false);//设置状态

        // 指定前端的请求域名
        String allowDomain = "http://localhost:8080";
        String allowDomain1 = "http://localhost:8081";
        String allowDomain2 = "http://39.96.116.78";
        String originHeads = request.getHeader("Origin");
        if(allowDomain.equals(originHeads) || allowDomain1.equals(originHeads) || allowDomain2.equals(originHeads)){
            //设置允许跨域的配置
            // 这里填写你允许进行跨域的主机ip（正式上线时可以动态配置具体允许的域名和IP）
            response.setHeader("Access-Control-Allow-Origin", originHeads);
        }

        response.setHeader("Access-Control-Allow-Credentials", "true");

        response.setHeader("Access-Control-Allow-Headers",
                "Content-Type,Content-Length, Authorization, Accept,X-Requested-With,token");

        response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");


        //将map转为json，使用jsckson
        String json = new ObjectMapper().writeValueAsString(generalResponse1);

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);

        return false;
    }
}
